package com.settlement.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.settlement.system.common.model.Option;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.EasyExcelImportUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.handler.disruptor.MessageVo;
import com.settlement.system.model.entity.SysBaseColumnMatch;
import com.settlement.system.model.entity.SysImportErrorDetail;
import com.settlement.system.model.entity.SysImportLog;
import com.settlement.system.model.vo.RPAImportVo;
import com.settlement.system.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 平台原始单据导入 控制类
 */
@Tag(name = "平台原始单据导入")
@RestController
@RequestMapping("/api/v1/sourceTable")
@RequiredArgsConstructor
public class PlatformSourceTableController {

    private final DisruptorMqService disruptorMqService;

    private final SysImportLogService sysImportLogService;

    private final SysImportErrorDetailService sysImportErrorDetailService;

    private final SysDictService dictService;

    private final SysBaseColumnMatchService sysBaseColumnMatchService;

    @Operation(summary = "原始订单和原始账单导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sourceImport")
    public Result<?> sourceImport(@Parameter(description = "平台和单据类型（淘宝订单(TB_order)、淘宝账单(TB_bill)") String platformAndType, @Parameter(description = "店铺") Long storeId, @RequestParam("file") MultipartFile file) {
        List<Map<String, String>> list = EasyExcelImportUtils.makeData(file, null, 0, 1);
        if (list.size() == 0) {
            return Result.success();
        }
        // 判断原始字段和数据字典字段是否相等
        List<Option> dictList = dictService.listDictOptions(platformAndType.replace("_", ""));
        List<String> dictLabelList = dictList.stream().map(Option::getLabel).toList();
        List<String> sourceColumnList = list.get(0).keySet().stream().toList();
        if (dictLabelList.size() != sourceColumnList.size()) {
            return Result.success("导入数据字段名称与平台配置的字段名称不一致，请重新导入平台字段名称再尝试");
        }
        if (sourceColumnList.stream().anyMatch(sourceColumn -> !dictLabelList.contains(sourceColumn.replaceAll(
                "\uFEFF", "")))) {
            return Result.success("导入数据字段名称与平台配置的字段名称不一致，请重新导入平台字段名称再尝试");
        }
        // 检查字段对应关系配置是否正确
        // 基础字段配置
        List<SysBaseColumnMatch> baseColumnMatchList = sysBaseColumnMatchService.getByPlatform(platformAndType.replace("_", ""));
        // 循环处理数据
        String value;
        Map<String, String> dataValue = new HashMap<>();
        for (String key : list.get(0).keySet()) {
            value = list.get(0).get(key);
            if (StringUtils.hasText(value)) {
                dataValue.put(key.strip().replaceAll("\uFEFF", ""), value.replaceAll("'", ""));
            } else {
                dataValue.put(key.strip().replaceAll("\uFEFF", ""), null);
            }
        }
        if (baseColumnMatchList.size() == 0) {
            return Result.failed("平台没有配置字段对应关系");
        }
        List<String> errorMsgList = new ArrayList<>();

        for (SysBaseColumnMatch sysBaseColumnMatch : baseColumnMatchList) {
            if (!dataValue.containsKey(sysBaseColumnMatch.getSourceColumn())) {
                errorMsgList.add("【%s】".formatted(sysBaseColumnMatch.getSourceColumn()));
            }
        }
        if (errorMsgList.size() > 0) {
            return Result.failed("导入表格缺少以下字段：%s，请添加字段再重新导入".formatted(String.join(",", errorMsgList)));
        }
        // 先生成一条导入记录
        SysImportLog sysImportLog = new SysImportLog();
        // 记录总数
        sysImportLog.setTotalCount(list.size());
        sysImportLog.setStoreAccountId(storeId);
        // 保存
        sysImportLogService.saveOrUpdate(sysImportLog);

        for (Map<String, String> dataMap : list) {
            MessageVo vo = new MessageVo();
            Map<String, String> data = new HashMap<>();
            for (String key : dataMap.keySet()) {
                value = dataMap.get(key);
                if (StringUtils.hasText(value)) {
                    data.put(key.strip().replaceAll("\uFEFF", ""), value.replaceAll("'", ""));
                } else {
                    data.put(key.strip().replaceAll("\uFEFF", ""), null);
                }
            }
            vo.setDataMap(data);
            // 设置日志ID
            vo.setLogId(sysImportLog.getId());
            disruptorMqService.handle(vo);
        }
        return Result.success("导入成功");
    }

    @Operation(summary = "RPA单据导入账单明细接口")
    @PostMapping("/rpaImport")
    public Result<?> rpaImport(@RequestBody RPAImportVo rpaImportVo) {
        MessageVo vo = new MessageVo();
        vo.setDataMap(rpaImportVo.getData());
        vo.setLogId(rpaImportVo.getLogId());
        vo.setDetailId(rpaImportVo.getDetailId());
        disruptorMqService.handle(vo);
        return Result.success("导入成功");
    }

    @Operation(summary = "RPA生成导入记录接口，返回日志ID，用于上传导入记录")
    @PostMapping("/rpaImportLog")
    public Result<?> rpaImportLog(@RequestBody SysImportLog sysImportLog) {
        return Result.success(sysImportLogService.insertOrUpdate(sysImportLog));
    }
}
